package cool.taomu.toolkit.plantuml

import cool.taomu.toolkit.crypto.Base64
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.StringWriter
import net.sourceforge.plantuml.FileFormat
import net.sourceforge.plantuml.FileFormatOption
import net.sourceforge.plantuml.SourceStringReader
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory
import cool.taomu.toolkit.template.ITemplate
import java.util.Map

class PlantumlUtils implements ITemplate {
	val static LOG = LoggerFactory.getLogger(PlantumlUtils);

	def generateUmlImage(String source) throws IOException {
		var SourceStringReader reader = new SourceStringReader(source);
		val output = new ByteArrayOutputStream();
		reader.getBlocks().forEach [ block |
			block.diagram.exportDiagram(output, 0, new FileFormatOption(FileFormat.SVG));
			LOG.info("PlantUml 图片生成成功");
		]
		return output
	}

	override execute(String path, Map<String, Object> dataModel) {
		var StringWriter writer = new StringWriter();
		try {
			var plantUmlByte = this.generateUmlImage(path).toByteArray
			writer.append(new String(new Base64(plantUmlByte).encode, "UTF-8"));
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer
	}

}
